package com.nanbei.cas;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @ClassDescription: CAS案例
 * @JdkVersion: 1.8
 * @Author: libs
 * @Created: 2024/10/9 10:43
 */
@Slf4j
public class CASLockExample {

    private AtomicBoolean locked = new AtomicBoolean(false);

    public void acquireLock() throws InterruptedException {

        // 忙等待条件的满足
        while (!locked.compareAndSet(false, true)) {
            // 空循环等待条件满足
        }
        TimeUnit.MILLISECONDS.sleep(1);
        log.info(Thread.currentThread().getName()+":线程获取的锁");
    }

    public void releaseLock() {
        locked.set(false);
        log.info( Thread.currentThread().getName()+"线程释放的锁" );
    }

    public static void main(String[] args) {
        final CASLockExample lock = new CASLockExample();

        // 创建多个线程并尝试获取锁
        for (int i = 1; i <= 5; i++) {
            final int threadId = i;
            new Thread(() -> {
                log.info("线程 " + threadId + " 试图获得锁.");
                try {
                    lock.acquireLock();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                // 模拟执行一些工作
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                lock.releaseLock();
            },"t"+i).start();
        }
    }
}
